package top.cluski.feieprint.api.teable.domain.dto;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import top.cluski.feieprint.api.teable.TeableApi;
import top.cluski.feieprint.api.teable.entity.RecordEntity;

import java.util.List;

import static top.cluski.feieprint.api.teable.entity.Filter.emptyFilter;

/**
 * 起步10分钟/公里，1公里之后，5分钟/公里
 */
@Data
@Accessors(chain = true)
@Slf4j
public class PaotuiConfig {
    int firstPeriodMinutes = 30;
    int minutesPerMile = 2;

    public static PaotuiConfig create() {
        return new PaotuiConfig();
    }

    public static PaotuiConfig fromTeable() {
        PaotuiConfig paotuiConfig = new PaotuiConfig();
        try {
            TeableApi teableApi = SpringUtil.getBean(TeableApi.class);
            List<RecordEntity> records = teableApi.getRecords("tblR87JMmLOhwzeow79", emptyFilter());
            for (RecordEntity record : records) {
                String title = record.getFields().getString("标题");
                if (StrUtil.equals("跑腿首公里时间（分钟）", title)) {
                    paotuiConfig.firstPeriodMinutes = Integer.parseInt(record.getFields().getString("值"));
                } else if (StrUtil.equals("跑腿后续公里每公里时间（分钟）", title)) {
                    paotuiConfig.minutesPerMile = Integer.parseInt(record.getFields().getString("值"));
                }
            }
        } catch (Exception e) {
            log.error("从teable中获取配送时间配置失败", e);
            paotuiConfig = create();
        }
        return paotuiConfig;
    }
}
